package com.albon.baseball;

import java.util.ArrayList;
import java.util.Calendar;


import com.albon.alarm.BaseballSetAlarm;
import com.albon.alarm.StaticVariable;
import com.albon.sportsalarm.R;
import com.albon.util.Logg;
import com.albon.util.ToastMaster;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class BaseballAdapter extends ArrayAdapter<Baseball> implements StaticVariable{
	private final String TAG = "BaseballAdapter";
	private ArrayList<Baseball> mItems;
	private LayoutInflater mInflater;
	
	private Context mContext;
	private Baseball baseball = null;
	private long set_alarm_time = 0L;
	private String [] notification_time_array_value = {};
	private String stadium;
	public BaseballAdapter(Context context, int resource, ArrayList<Baseball> items) 
	{
		super(context, resource, items);
		mContext=context;
		mItems = items;
		Logg.d(TAG, "items.size() : "+items.size());
		mInflater = LayoutInflater.from(context);
		notification_time_array_value = context.getResources().getStringArray(R.array.notification_time_array_value);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		if(convertView == null)
		{
			convertView = mInflater.inflate(R.layout.sports_row_item, null);
		}
		

		final int index=position;
		LinearLayout alarm_icon = (LinearLayout)convertView.findViewById(R.id.alarm_icon);
    	LinearLayout alarm_impassible = (LinearLayout)convertView.findViewById(R.id.alarm_impassible);
    	Logg.d(TAG, "alarm_icon : "+alarm_icon);
    	Logg.d(TAG, "impossible_alarm : "+alarm_impassible);
    	alarm_icon.setVisibility(View.GONE);
    	alarm_impassible.setVisibility(View.GONE);
		View indicator = convertView.findViewById(R.id.indicator);
		final ImageView iv = (ImageView)indicator.findViewById(R.id.button_toggle);
		
		TextView game_progress = (TextView)convertView.findViewById(R.id.game_progress);
		TextView score_a = (TextView)convertView.findViewById(R.id.score_a);
		TextView score_b = (TextView)convertView.findViewById(R.id.score_b);
		
		TextView real_date = (TextView)convertView.findViewById(R.id.real_date);
		
		TextView stadium = (TextView)convertView.findViewById(R.id.stadium);
		TextView a_team = (TextView)convertView.findViewById(R.id.a_team);
		TextView b_team = (TextView)convertView.findViewById(R.id.b_team);
		String month = mItems.get(index).getReal_date().substring(0, mItems.get(index).getReal_date().indexOf("월"));
		String day = mItems.get(index).getReal_date().substring(mItems.get(index).getReal_date().indexOf(" "), mItems.get(index).getReal_date().indexOf("일")).trim();
		
		day = day.length()==1?"0"+day:day;
		real_date.setText(month+"."+day+" "+mItems.get(index).getReal_time());
		
		stadium.setText(mItems.get(index).getStadium());
		a_team.setText(mItems.get(index).getA_team());
		b_team.setText(mItems.get(index).getB_team());
		
		Logg.d(TAG, "mItems.get(index).getScore() :"+mItems.get(index).getScore()+"//");
		Logg.d(TAG, "mItems.get(index).getScore() : "+mItems.get(index).getScore().length());
		if(mItems.get(index).getScore().length()>2){
			alarm_icon.setVisibility(View.GONE);
			alarm_impassible.setVisibility(View.VISIBLE);
			game_progress.setText(mContext.getText(R.string.finish).toString());
			
			score_a.setText(mItems.get(index).getScore().substring(0, mItems.get(index).getScore().indexOf(":")));
			score_b.setText(mItems.get(index).getScore().substring(mItems.get(index).getScore().indexOf(":")+1));
		}else{
			alarm_icon.setVisibility(View.VISIBLE);
			alarm_impassible.setVisibility(View.GONE);
			
		}
		
		final Baseball baseballItem = (Baseball)mItems.get(index); 
		convertView.setTag(baseballItem);
		final boolean isClick = baseballItem.isBtnClicked();
		final String mYear = baseballItem.getmYear();
		final String mMonth = baseballItem.getmMonth();
		
		if(isClick){
			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alarm_on));
		}else{
			iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alarm_off));
		}
		indicator.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
               if(mItems.get(index).getScore().equals(":")){
					if(mItems.get(index).isBtnClicked()){
					//	Logg.d(TAG, "1");
						iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alarm_off));
	//					update_values(mItems.get(index).getId(), false);
						call_alarm_key(mItems.get(index).getAlarm_title(), mYear, mMonth, mItems.get(index).getReal_date(),mItems.get(index).getReal_time(), mItems.get(index).getCompare_date(), mItems.get(index).getA_team(), mItems.get(index).getB_team(), mItems.get(index).getStadium(), false);
					}else{
					//	Logg.d(TAG, "2");
						iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alarm_on));
						//update_values(mItems.get(index).getId(), true);
						call_alarm_key(mItems.get(index).getAlarm_title(), mYear, mMonth, mItems.get(index).getReal_date(),mItems.get(index).getReal_time(), mItems.get(index).getCompare_date(), mItems.get(index).getA_team(), mItems.get(index).getB_team(), mItems.get(index).getStadium(), true);
					}
					mItems.get(index).setBtnClicked(!mItems.get(index).isBtnClicked());
				}else{
					Toast.makeText(mContext, R.string.past_game, Toast.LENGTH_SHORT).show();	
				}
			}
		});
		return convertView;
	}	
	
	@Override
	public int getCount() {
		
		return mItems.size();//자료의 총 갯수를 리턴한다.
	}

	@Override
	public Baseball getItem(int position) {
		
		return mItems.get(position);//인자로 넘어오는 인덱스에 해당하는 객체를 리턴한다.
	}

	@Override
	public long getItemId(int position) {
		
		return position; //중복되지 않는 id 역활을 position 이 할수있다.
	}
	
	/*=============================================================================================================*/	
	//저장된 알람 업데이트
    public void update_values(int alarmId, boolean enable){ 
    	
    	cancelAlarm(alarmId);
    	
		SQLiteDatabase databse = null;
		if(databse == null){
			databse = mContext.openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}		
		
		String _id = String.valueOf(alarmId);		
	
		String enabled = String.valueOf(enable);	
		
		ContentValues values = new ContentValues();		

		values.put(DatabaseHelper.DATABASE_COLUMN_ENABLED, enabled);
	
		
		long uid = databse.update(DatabaseHelper.DATABASE_TABLE_NAME, values, "_id=?", new String [] {_id});
		if(uid == -1){			
			Logg.e(TAG, "db update - error occurred");
		}else{
			if(enable){
				setAlarm(alarmId);
			}
		}
		if(databse != null){
			databse.close();
			databse = null;
		}
		
	}
    
    //알람 취소
    private void cancelAlarm(int key)
	{
    	AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(ALARM_BASEBALL_ALERT_ACTION);
		intent.putExtra("key", key);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, key, intent, 0);
		
		if(am != null)
		{
			am.cancel(sender);
			am = null;
		}
	
	}
    
    //알람 설정
    void setAlarm(int key){
    	Intent intent_send = new Intent(ALARM_BASEBALL_ALERT_ACTION);
    	intent_send.putExtra("key", key);
    	PendingIntent sender = PendingIntent.getBroadcast(mContext, key, intent_send, 0);
		AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, set_alarm_time, sender);
		popAlarmSetToast(mContext, set_alarm_time);
    }
    
    private static void popAlarmSetToast(Context context, long timeInMillis) {
        String toastText = formatToast(context, timeInMillis);
        Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
        ToastMaster.setToast(toast);
        toast.show();
      
    }
    
	 /**
     * Toast 설정
     * 
     */
    static String formatToast(Context context, long timeInMillis) {
        long delta = timeInMillis - System.currentTimeMillis();
        long hours = delta / (1000 * 60 * 60);
        long minutes = delta / (1000 * 60) % 60;
        long days = hours / 24;
        hours = hours % 24;

        String daySeq = (days == 0) ? "" :
                (days == 1) ? context.getString(R.string.day) :
                context.getString(R.string.days, Long.toString(days));

        String minSeq = (minutes == 0) ? "" :
                (minutes == 1) ? context.getString(R.string.minute1) :
                context.getString(R.string.minutes, Long.toString(minutes));

        String hourSeq = (hours == 0) ? "" :
                (hours == 1) ? context.getString(R.string.hour1) :
                context.getString(R.string.hours, Long.toString(hours));

        boolean dispDays = days > 0;
        boolean dispHour = hours > 0;
        boolean dispMinute = minutes > 0;

        int index = (dispDays ? 1 : 0) |
                    (dispHour ? 2 : 0) |
                    (dispMinute ? 4 : 0);

        String[] formats = context.getResources().getStringArray(R.array.alarm_set);
        return String.format(formats[index], daySeq, hourSeq, minSeq);
    }
    
    private void call_alarm_key(String league_title, String mYear, String mMonth, String real_date, String real_time, String key_compare_date, String key_a_team, String key_b_team, String stadium, Boolean enable){
    	
    	SQLiteDatabase databse = null;	
    	boolean flag = true;
    	int key = 1;
    	int notification_time_value = 0;
		if(databse == null){
			databse = mContext.openOrCreateDatabase(DatabaseHelper.DATABASE_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		}
		String stringWhere = " WHERE " + DatabaseHelper.DATABASE_COLUMN_COMPARE_DATE + " = '" +key_compare_date+"' and "+ DatabaseHelper.DATABASE_COLUMN_A_TEAM +" = '"+key_a_team+"' and "+DatabaseHelper.DATABASE_COLUMN_B_TEAM+" = "+"'"+key_b_team+"'";		
		
		Cursor cursor = null;

		try { //where 값으로 key 값 먼저 검색
			cursor = databse.rawQuery("SELECT "
					+ DatabaseHelper.DATABASE_COLUMN_ID + ", "
					+ DatabaseHelper.DATABASE_COLUMN_NOTIFICATION + " " + " FROM "
					+ DatabaseHelper.DATABASE_TABLE_NAME + " " + stringWhere, null);
			if (cursor != null && cursor.moveToFirst()) {
				do {	
					key = cursor.getInt(0);
					notification_time_value = Integer.parseInt(cursor.getString(1));
					flag = false;
				} while (cursor.moveToNext());
				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				long cur_time = calendar.getTimeInMillis();
				
				
				/*Logg.d(TAG, "key_compare_date : "+key_compare_date);		
				Logg.d(TAG, "day : "+key_compare_date.substring(6));
				Logg.d(TAG, "real_time 1: "+real_time.substring(0, 2));
				Logg.d(TAG, "real_time 2: "+real_time.substring(3));*/
				
				String day = key_compare_date.substring(6);
				String hour = real_time.substring(0, 2);
				String minute = real_time.substring(3);
				calendar.set(Calendar.YEAR, Integer.parseInt(mYear));
				calendar.set(Calendar.MONTH, Integer.parseInt(mMonth)-1);
				calendar.set(Calendar.DATE, Integer.parseInt(day));
				calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
				calendar.set(Calendar.MINUTE, Integer.parseInt(minute));
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				
				if(notification_time_value==0){
					set_alarm_time = calendar.getTimeInMillis();
				}else{
					set_alarm_time = calendar.getTimeInMillis()-Long.valueOf(notification_time_array_value[notification_time_value]);
				}
				update_values(key, enable); //DB 업데이트
			}		
					
			if(flag){ // where 값이 없을 때  알람 세팅 화면 호출
				Intent set_alarm_intent = new Intent(mContext, BaseballSetAlarm.class);
				set_alarm_intent.putExtra("league_title", league_title);
				set_alarm_intent.putExtra("compare_date", key_compare_date);
				set_alarm_intent.putExtra("a_team", key_a_team);
				set_alarm_intent.putExtra("b_team", key_b_team);
				set_alarm_intent.putExtra("real_date", real_date);
				set_alarm_intent.putExtra("real_time", real_time);
				set_alarm_intent.putExtra("year", mYear);
				set_alarm_intent.putExtra("month", mMonth);
				set_alarm_intent.putExtra("stadium", stadium);
				set_alarm_intent.putExtra("enable", true);
				mContext.startActivity(set_alarm_intent);
				/*try {
					cursor = databse.rawQuery("SELECT "
							+ DatabaseHelper.DATABASE_COLUMN_ID + " " + " FROM "
							+ DatabaseHelper.DATABASE_TABLE_NAME , null);
									
						if (cursor != null && cursor.moveToFirst()) {					
							try{
								do {
									key = cursor.getInt(0);									
								} while (cursor.moveToNext());
								
							}catch (Exception e2) {
								// TODO: handle exception
								Logg.e(TAG, "e2 "+e2);
							}
						}
				}catch (Exception e) {
					// TODO: handle exception
				}*/
			}
		} finally {
			if (cursor != null)
				cursor.close();
			if(databse != null){
				databse.close();
			}
		}
		
    }



}
